﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Text;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Openfree.Framework.DataAccess;

public partial class Controls_Activity_GoodItems : BaseUserControl
{
    private GoodsCategoryAccess goodsCategoryAccess;
    private bool m_IsShowPrice = false;
    public bool IsShowPrice
    {
        get
        {
            return m_IsShowPrice;
        }
        set
        {
            m_IsShowPrice = value;
        }
    }
    private string cmdItemsText = "SELECT T.*,C.ActiveCount,A.SUBJECT AS CategoryName FROM {0} T inner join IC_Goods C on C.GoodsId=T.GoodsId LEFT JOIN " + GoodsCategoryAccess.TABLE_NAME + " A ON A.NODEID=T.CategoryID where 1=1 ";

    private string cmdGoodsText = string.Format("SELECT T.*,A.SUBJECT AS CategoryName FROM {0} T LEFT JOIN " + GoodsCategoryAccess.TABLE_NAME + " A ON A.NODEID=T.CategoryID where 1=1 ", "IC_Goods");

    private bool m_IsReadOnly;
    public bool IsReadOnly
    {
        get { return m_IsReadOnly; }
        set { m_IsReadOnly = value; }
    } 
    public string GoodCountCaption
    {
        get { return hfCountHeaderText.Value; }
        set { hfCountHeaderText.Value = value; }
    } 
    public EventHandler OnSelect;
 
    //注意 btnModalPopupOK_Click 事件代码
    //调用 GoodItems 的地方要注册 OnGoodItemSelect 事件
    //响应事件函数时候，参数 e 里面就有 相关数据了 e.SelectDataSet

    protected void Page_Load(object sender, EventArgs e)
    { 
        goodsCategoryAccess = new GoodsCategoryAccess(base.Connection);
        if (!IsPostBack)
        { 
        }
        OnSelect += new EventHandler(btnShowSelectItem);
        GoodItemSelect.OnGoodItemSelectOk += new GoodItemSelectEventHandler(btnSelectOk_Click); 
    }

    public void ItemsClear()
    {
        gridViewItems.DataSource = null;
        gridViewItems.DataBind();
    }
    private void btnSelectOk_Click(object sender, EventArgs e)
    {

        BindGridViewItems();
    }
    private void btnShowSelectItem(object sender, EventArgs e)
    {
        GoodItemSelect.OnSelect(sender, e);
    }
    public bool PreProcessSave()
    {
        DataTable dt = SessionManager.DataSet.Tables[SessionManager.GetValue(PMSConst.m_TableItemName).ToString()];
         
        //控制被删除的行
        int n = -1;
        for (int i = 0; i < gridViewItems.Rows.Count; i++)
        {
            n++;
            if (dt.Rows[n].RowState == DataRowState.Deleted)
            { 
                i--;
                continue;
            }
            int count = 0;
            decimal cost = 0;
            int badcount = 0;
            try
            {
                count = Convert.ToInt32((gridViewItems.Rows[i].Cells[6].Controls[3] as TextBox).Text);
                if (IsShowPrice)
                    cost = Convert.ToDecimal((gridViewItems.Rows[i].Cells[7].Controls[1] as TextBox).Text);

                if ("退回数量" == hfCountHeaderText.Value)
                {
                    badcount = Convert.ToInt32((gridViewItems.Rows[i].Cells[10].Controls[1] as TextBox).Text);
                }
            }
            catch
            {
                base.Alert("数量请输入整数，价格请输入整数或浮点数，其它值无效！");
                return false;
            }
            dt.Rows[n]["GoodsCount"] = count; 
            dt.Rows[n]["BadCount"] = badcount;
            dt.Rows[n]["StandardCost"] = cost;
            dt.Rows[n]["CountCost"] = count*cost;
            //dt.Rows[i]["TaxCount"] = (gridViewItems.Rows[i].Cells[9].Controls[1] as TextBox).Text;
            dt.Rows[n]["Description"] = (gridViewItems.Rows[i].Cells[9].Controls[1] as TextBox).Text;
        }
        if (n == -1)
        { 
            base.Alert("请选择具体物料项！");
            return false;
        }
        return true;
    }
    public void InitData(string tablename,string key,string subkey,string subvalue)
    {
        SessionManager.SetValue(PMSConst.m_TableItemName, tablename);
        SessionManager.SetValue(PMSConst.m_Key, key);
        SessionManager.SetValue(PMSConst.m_SubKey, subkey);
        SessionManager.SetValue(PMSConst.m_SubValue, subvalue);
        string cmdtext = string.Format(cmdItemsText, tablename);
        if (!string.IsNullOrEmpty(subvalue))
            cmdtext += " AND " + subkey + " = '" + subvalue + "' ";
        else
            cmdtext += " AND 1=2 ";
        PMSAccess.FillDataSet(this.Connection,SessionManager.DataSet, cmdtext, tablename);
        BindGridViewItems();
    }
    public void InitStackInData(string tablename, string key, string subkey, string subvalue)
    {
        SessionManager.SetValue(PMSConst.m_TableItemName, tablename);
        SessionManager.SetValue(PMSConst.m_Key, key);
        SessionManager.SetValue(PMSConst.m_SubKey, subkey);
        SessionManager.SetValue(PMSConst.m_SubValue, subvalue);
        string cmdtext = string.Format(cmdItemsText, tablename);
        cmdtext += " AND 1=2 ";
        PMSAccess.FillDataSet(this.Connection, SessionManager.DataSet, cmdtext, tablename);
        if(SessionManager.DataSet.Tables.Contains("IC_PurchaseOrderItem"))
        {
            DataRow _dr = null;
            foreach (DataRow dr in SessionManager.DataSet.Tables["IC_PurchaseOrderItem"].Rows)
            {
                _dr = SessionManager.DataSet.Tables[tablename].NewRow();
                _dr[SessionManager.GetValue(PMSConst.m_Key).ToString()] = System.Guid.NewGuid().ToString();
                _dr[SessionManager.GetValue(PMSConst.m_SubKey).ToString()] = SessionManager.GetValue(PMSConst.m_SubValue);
                _dr["GoodsID"] = dr["GoodsID"];
                _dr["GoodsCode"] = dr["GoodsCode"];
                _dr["Subject"] = dr["Subject"];
                _dr["CategoryName"] = dr["CategoryName"];
                _dr["CategoryID"] = dr["CategoryID"];
                _dr["GoodsMaker"] = dr["GoodsMaker"];
                _dr["TypeModel"] = dr["TypeModel"];
                _dr["GoodsUnit"] = dr["GoodsUnit"];
                _dr["GoodsCount"] = dr["GoodsCount"];
                _dr["StandardCost"] = dr["StandardCost"];
                _dr["CountCost"] = dr["CountCost"];
                //_dr["TaxCount"] = dr["TaxCount"];
                _dr["Description"] = dr["Description"];
                SessionManager.DataSet.Tables[tablename].Rows.Add(_dr);
            }
        }
        BindGridViewItems();
    } 


    #region 具体项操作
    protected void BindGridViewItems()
    {
        DataTable dt = SessionManager.DataSet.Tables[SessionManager.GetValue(PMSConst.m_TableItemName).ToString()];

        if (!dt.Columns.Contains("BadCount"))
        {
            dt.Columns.Add("BadCount", typeof(Int32));
        } 
        if (!dt.Columns.Contains("OutCount"))
        {
            dt.Columns.Add("OutCount", typeof(Int32));
        }
        if (dt.TableName == "IC_StockOutItem")
        {
            foreach (DataRow dr in dt.Rows)
            {
                dr["OutCount"] = dr["GoodsCount"];
            }
        }
        gridViewItems.Columns[6].HeaderText = GoodCountCaption;
        gridViewItems.ShowFooter = false;
        gridViewItems.DataSource = dt;
        gridViewItems.DataBind();
        gridViewItems.Columns[7].Visible = IsShowPrice;
        gridViewItems.Columns[8].Visible = IsShowPrice;
        if ("退回数量" == hfCountHeaderText.Value)
        {
            gridViewItems.Columns[10].Visible = true;
        }
        else
        {
            gridViewItems.Columns[10].Visible = false;
        } 
        if ("采购数量" == hfCountHeaderText.Value)
        {
            gridViewItems.Columns[11].Visible = false;
        }
        else
        {
            gridViewItems.Columns[11].Visible = true;
        }

    } 
    protected void gridViewItems_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //if (e.Row.RowType == DataControlRowType.Header)
        //{
        //    gridViewItems.Columns[6].HeaderText = GoodCountCaption;
        //}
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ((HyperLink)e.Row.Cells[0].Controls[0]).NavigateUrl = "~/PMSWeb/GoodDetail.aspx?GoodsID=" + ((HiddenField)e.Row.Cells[6].Controls[1]).Value;
            if (IsReadOnly)
            {
                (e.Row.Cells[6].Controls[3] as TextBox).ReadOnly = true;
                (e.Row.Cells[7].Controls[1] as TextBox).ReadOnly = true;
                (e.Row.Cells[9].Controls[1] as TextBox).ReadOnly = true;
                (e.Row.Cells[13].Controls[0]).Visible = false; 
            }
            else
            {
                (e.Row.Cells[6].Controls[3] as TextBox).ReadOnly = false;
                (e.Row.Cells[7].Controls[1] as TextBox).ReadOnly = false;
                (e.Row.Cells[9].Controls[1] as TextBox).ReadOnly = false;
                (e.Row.Cells[13].Controls[0]).Visible = true; 
            }
        }
    }

    protected void gridViewItems_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string tbn = SessionManager.GetValue(PMSConst.m_TableItemName).ToString();
        string ID = (gridViewItems.Rows[e.RowIndex].Cells[6].Controls[1] as HiddenField).Value;
        foreach (DataRow row in SessionManager.DataSet.Tables[tbn].Rows)
        {
            if (row.RowState != DataRowState.Deleted && ID.Equals(row["GoodsID"].ToString()))
            {
                row.Delete();
                BindGridViewItems();
                break;
            }
        }
    }
    #endregion 
} 
